package telebasesimple;

import dblib.DB;
import java.awt.Image;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.RowFilter.Entry;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

public class MainFrame extends javax.swing.JFrame {

    public MainFrame() {
        initComponents();

        ImageIcon imageicon = new ImageIcon(getClass().getResource("/telebasesimple/resources/icon.png"));
        Image image = imageicon.getImage();
        this.setIconImage(image);

        this.setTitle(Vars.getVersion());

        DefaultTableModel tablemodel = new DefaultTableModel(
                new Object[][]{},
                new String[]{"Имя", "Должность", "Телефон"}) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(tablemodel);
        jTable1.setModel(tablemodel);
        jTable1.setRowSorter(sorter);

        jTable1.getColumnModel().getColumn(0).setPreferredWidth(325);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(425);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(250);

        this.setMinimumSize(this.getSize());

        jTextField1.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent de) {
                filterTable();
            }

            @Override
            public void removeUpdate(DocumentEvent de) {
                filterTable();
            }

            @Override
            public void changedUpdate(DocumentEvent de) {
                filterTable();
            }
        });

        refreshTable();
    }

    private void filterTable() {
        RowFilter<DefaultTableModel, Integer> rowfilter = new RowFilter<DefaultTableModel, Integer>() {

            @Override
            public boolean include(Entry<? extends DefaultTableModel, ? extends Integer> entry) {
                String str = entry.getValue(0).toString() + " " + entry.getValue(1).toString() + " " + entry.getValue(2).toString();
                str = str.toLowerCase();
                str = str.trim();
                str = str.replaceAll("   ", " ");
                str = str.replaceAll("-", "");
                if (str.contains(jTextField1.getText().toLowerCase())) {
                    return true;
                }
                return false;
            }
        };
        TableRowSorter<DefaultTableModel> sorter = (TableRowSorter<DefaultTableModel>) jTable1.getRowSorter();
        sorter.setRowFilter(rowfilter);
    }

    private void refreshTable() {
        DB db = new DB();

        String sql = "SELECT people.k, people.name, people.job, p1.k, p1.phone "
                + "FROM (SELECT * FROM phones WHERE phones.hide = 0) AS p1 "
                + "RIGHT OUTER JOIN people ON people.k = p1.p_id "
                + "WHERE people.hide = 0";
        ResultSet rs = db.getResultSet(sql);

        DefaultTableModel tm = (DefaultTableModel) jTable1.getModel();
        while (tm.getRowCount() > 0) {
            tm.removeRow(0);
        }

        try {
            while (rs.next()) {
                Integer p_id = rs.getInt("people.k");
                String Name = DB.getStringFromHex(rs.getString("people.name"));
                String Job = DB.getStringFromHex(rs.getString("people.job"));
                String Phone = DB.getStringFromHex(rs.getString("p1.phone"));
                Integer P_k = rs.getInt("p1.k");

                Boolean co_exists = false;

                for (int rowid = 0; rowid < tm.getRowCount(); rowid++) {
                    Contact co = (Contact) tm.getValueAt(rowid, 0);
                    if (co.getP_id().equals(p_id)) {
                        co.addPhone(P_k, Phone);
                        tm.setValueAt(co.getPhonesString(), rowid, 2);
                        co_exists = true;
                    }
                }
                if (!co_exists) {
                    Contact co = new Contact(p_id, Name, Job);
                    if (Phone != null) {
                        co.addPhone(P_k, Phone);
                    }
                    Object[] rowdata = new Object[3];
                    rowdata[0] = co;
                    rowdata[1] = co.getJob();
                    rowdata[2] = co.getPhonesString();
                    tm.addRow(rowdata);
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        db.closeResultSet();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jButton1.setText("Закрыть");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Добавить...");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/telebasesimple/resources/reload.png"))); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton4.setText("Удалить");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Правка...");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 830, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 410, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 768, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton5)
                    .addComponent(jButton4))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    dispose();
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    jTextField1.setText("");
    jTextField1.requestFocus();
    refreshTable();
}//GEN-LAST:event_jButton3ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    AddContactDialog dlg = new AddContactDialog(this, true);
    dlg.setLocationRelativeTo(null);
    dlg.setVisible(true);
    refreshTable();
}//GEN-LAST:event_jButton2ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        if (jTable1.getSelectedRow() == -1) {
            return;
        }

        if (JOptionPane.showConfirmDialog(
                null,
                "Вы уверены, что хотите удалить эту запись?",
                "Подтверждение",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            Contact co = (Contact) jTable1.getValueAt(jTable1.getSelectedRow(), 0);
            DB db = new DB();
            db.executeNonQuery("UPDATE people SET `hide` = true WHERE k = " + co.getP_id().toString());
            refreshTable();
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        if (jTable1.getSelectedRow() == -1) {
            return;
        }
        Contact co = (Contact) jTable1.getValueAt(jTable1.getSelectedRow(), 0);
        EditContachDialog dlg = new EditContachDialog(this, true, co);
        dlg.setLocationRelativeTo(null);
        dlg.setVisible(true);
        if (dlg.isContactChanged) {
            refreshTable();
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        if (evt.getClickCount() > 1 && jTable1.getSelectedRowCount() > 0) {
            Contact co = (Contact) jTable1.getValueAt(jTable1.getSelectedRow(), 0);
            ViewContactDialog dlg = new ViewContactDialog(this, true, co);
            dlg.setLocationRelativeTo(null);
            dlg.setVisible(true);
            if (dlg.isContactChanged) {
                refreshTable();
            }
        }
    }//GEN-LAST:event_jTable1MouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
